import React, { useEffect, useState } from 'react';
import { Table, Button, Card, message, Space, Tooltip, Modal, Alert, Form, Input } from 'antd';
import { DownloadOutlined, FileExcelOutlined, FileTextOutlined, SaveOutlined, EditOutlined } from '@ant-design/icons';
import { TaskReport } from './models/aiReportsModels';
import { 
  getTaskReportList, 
  exportTaskReportExcel, 
  generateWeeklyReportDetail, 
  generateWeeklyReportHtml,
  downloadHtmlFile,
  saveHtmlToServer,
  updateTaskReport
} from '@/services/aireportService';
import { getUser } from '../../utils/auth';
/**
 * 任务报告表格页面
 */
const AiReportsPage: React.FC = () => {
  // 状态定义
  const [loading, setLoading] = useState<boolean>(false);
  const [data, setData] = useState<TaskReport[]>([]);
  const [exportLoading, setExportLoading] = useState<boolean>(false);
  const [generateDetailLoading, setGenerateDetailLoading] = useState<boolean>(false);
  const [generateHtmlLoading, setGenerateHtmlLoading] = useState<boolean>(false);
  const [editModalVisible, setEditModalVisible] = useState<boolean>(false);
  const [editingRecord, setEditingRecord] = useState<TaskReport | null>(null);
  const [form] = Form.useForm();

  // 获取当前用户信息（这里需要根据实际的用户信息获取方式调整）
  const getCurrentUser = () => {
      // 获取登录用户信息
      const userInfo = getUser();
      // 获取用户英文名
      const username = userInfo?.englishName || '';
       console.log('Current User:', username);
      return username;
  };

  // 判断当前用户是否有编辑权限
  const hasEditPermission = () => {
    const currentUser = getCurrentUser();
    const allowedUsers = ['ryanwu', 'selinacchen', 'janewang'];
    return allowedUsers.includes(currentUser);
  };

  // 表头样式
  const headerStyle = {
    backgroundColor: '#e6e9f0', 
    fontWeight: 600, 
    color: '#262626',
    fontSize: '15px'
  };

  // 表格列定义
  const columns = [
    {
      title: '任务标题',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      fixed: 'left' as const,
      onHeaderCell: () => ({ style: headerStyle }),
      render: (text: string) => (
        <div style={{ 
          whiteSpace: 'pre-wrap', 
          wordBreak: 'break-word',
          lineHeight: '1.5',
          padding: '4px 0'
        }}>{text || '-'}</div>
      ),
    },
    {
      title: '负责人',
      dataIndex: 'receiver',
      key: 'receiver',
      width: 120,
      fixed: 'left' as const,
      onHeaderCell: () => ({ style: headerStyle }),
      render: (text: string) => (
        <div style={{ 
          whiteSpace: 'pre-wrap', 
          wordBreak: 'break-word',
          lineHeight: '1.5',
          padding: '4px 0'
        }}>{text || '-'}</div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      onHeaderCell: () => ({ style: headerStyle }),
      render: (status: string) => {
        const statusMap: Record<string, { text: string; color: string }> = {
          todo: { text: '待办', color: '#faad14' },
          inProgress: { text: '进行中', color: '#1890ff' },
          done: { text: '已完成', color: '#52c41a' },
        };
        const { text, color } = statusMap[status] || { text: status, color: '#000' };
        return <span style={{ color }}>{text}</span>;
      },
    },
    {
      title: '需求类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      onHeaderCell: () => ({ style: headerStyle }),
    },
    {
      title: '子类型',
      dataIndex: 'subType',
      key: 'subType',
      width: 150,
      onHeaderCell: () => ({ style: headerStyle }),
    },
    {
      title: '业务部门',
      dataIndex: 'busiDepartment',
      key: 'busiDepartment',
      width: 120,
      onHeaderCell: () => ({ style: headerStyle }),
      render: (text: string) => (
        <div style={{ 
          whiteSpace: 'pre-wrap', 
          wordBreak: 'break-word',
          lineHeight: '1.5',
          padding: '4px 0'
        }}>{text || '-'}</div>
      ),
    },
    {
      title: '业务目标',
      dataIndex: 'busiGoal',
      key: 'busiGoal',
      width: 200,
      onHeaderCell: () => ({ style: headerStyle }),
      render: (text: string) => (
        <div style={{ 
          whiteSpace: 'pre-wrap', 
          wordBreak: 'break-word',
          lineHeight: '1.5',
          padding: '4px 0'
        }}>{text || '-'}</div>
      ),
    },
    {
      title: 'IT部门',
      dataIndex: 'itDepartment',
      key: 'itDepartment',
      width: 120,
      onHeaderCell: () => ({ style: headerStyle }),
      render: (text: string) => (
        <div style={{ 
          whiteSpace: 'pre-wrap', 
          wordBreak: 'break-word',
          lineHeight: '1.5',
          padding: '4px 0'
        }}>{text || '-'}</div>
      ),
    },
    {
      title: '预计进展',
      dataIndex: 'originalPlan',
      key: 'originalPlan',
      width: 250,
      onHeaderCell: () => ({ style: headerStyle }),
      render: (text: string) => (
        <div style={{ 
          whiteSpace: 'pre-wrap', 
          wordBreak: 'break-word',
          lineHeight: '1.5',
          padding: '4px 0',
          minHeight: '60px'
        }}>{text || '-'}</div>
      ),
    },
    {
      title: '实际进展',
      dataIndex: 'actualProgress',
      key: 'actualProgress',
      width: 250,
      onHeaderCell: () => ({ style: headerStyle }),
      render: (text: string) => (
        <div style={{ 
          whiteSpace: 'pre-wrap', 
          wordBreak: 'break-word',
          lineHeight: '1.5',
          padding: '4px 0',
          minHeight: '60px'
        }}>{text || '-'}</div>
      ),
    },
    {
      title: '存在问题',
      dataIndex: 'problems',
      key: 'problems',
      width: 250,
      onHeaderCell: () => ({ style: headerStyle }),
      render: (text: string) => (
        <div style={{ 
          whiteSpace: 'pre-wrap', 
          wordBreak: 'break-word',
          lineHeight: '1.5',
          padding: '4px 0',
          minHeight: '60px'
        }}>{text || '-'}</div>
      ),
    },
    {
      title: 'AI评价',
      dataIndex: 'progressRating',
      key: 'progressRating',
      width: 180,
      onHeaderCell: () => ({ style: headerStyle }),
      render: (text: string) => (
        <div style={{ 
          whiteSpace: 'pre-wrap', 
          wordBreak: 'break-word',
          lineHeight: '1.5',
          padding: '4px 0',
          minHeight: '60px'
        }}>{text || '-'}</div>
      ),
    },
    {
      title: 'AI总结',
      dataIndex: 'progressSummary',
      key: 'progressSummary',
      width: 320,
      onHeaderCell: () => ({ style: headerStyle }),
      render: (text: string) => (
        <div style={{ 
          whiteSpace: 'pre-wrap', 
          wordBreak: 'break-word',
          lineHeight: '1.5',
          padding: '4px 0',
          minHeight: '60px'
        }}>{text || '-'}</div>
      ),
    },
    {
      title: '周期结束日期',
      dataIndex: 'periodEndDate',
      key: 'periodEndDate',
      width: 120,
      onHeaderCell: () => ({ style: headerStyle }),
    },
    // 操作列 - 只有特定用户才显示
    ...(hasEditPermission() ? [{
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right' as const,
      onHeaderCell: () => ({ style: headerStyle }),
      render: (_: any, record: TaskReport) => (
        <Button
          type="primary"
          size="small"
          icon={<EditOutlined />}
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>
      ),
    }] : []),
  ];

  // 获取任务报告列表数据
  const fetchData = async () => {
    try {
      setLoading(true);
      const response = await getTaskReportList();
      setData(response.data);
    } catch (error) {
      console.error('获取任务报告列表失败:', error);
      message.error('获取任务报告列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 导出Excel
  const handleExportExcel = async () => {
    try {
      setExportLoading(true);
      await exportTaskReportExcel();
      message.success('导出Excel成功');
    } catch (error) {
      console.error('导出Excel失败:', error);
      message.error('导出Excel失败');
    } finally {
      setExportLoading(false);
    }
  };

  // 生成周报明细
  const handleGenerateDetail = async () => {
    try {
      setGenerateDetailLoading(true);
      await generateWeeklyReportDetail();
      message.success('生成周报明细成功');
      fetchData(); // 刷新数据
    } catch (error) {
      console.error('生成周报明细失败:', error);
      message.error('生成周报明细失败');
    } finally {
      setGenerateDetailLoading(false);
    }
  };

  // 生成周报HTML
  const handleGenerateHtml = async () => {
    try {
      setGenerateHtmlLoading(true);
      const response = await generateWeeklyReportHtml();
      const htmlContent = response.data;
      
      // 创建新窗口并显示HTML内容
      const newWindow = window.open('', '_blank');
      if (newWindow) {
        newWindow.document.write(htmlContent);
        newWindow.document.close();
      } else {
        message.warning('请允许浏览器打开新窗口');
      }
      
      // 显示操作确认对话框
      Modal.confirm({
        title: '周报HTML生成成功',
        content: '您想要执行什么操作？',
        okText: '下载HTML',
        cancelText: '取消',
        okButtonProps: { type: 'primary' },
        onOk: () => {
          // 下载HTML文件
          downloadHtmlFile(htmlContent, 'AI虚拟架构组周报');
        },
        footer: (_, { OkBtn, CancelBtn }) => (
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', gap: '8px' }}>
              <Button 
                icon={<SaveOutlined />}
                onClick={() => {
                  // 保存到服务器
                  saveHtmlToServer(htmlContent)
                    .then(() => {
                      message.success('HTML已成功保存到服务器');
                      Modal.destroyAll();
                    })
                    .catch((error: any) => {
                      console.error('保存HTML到服务器失败:', error);
                      message.error('保存HTML到服务器失败');
                    });
                }}
              >
                保存到服务器
              </Button>
              <Button 
                icon={<DownloadOutlined />}
                type="primary"
                onClick={() => {
                  downloadHtmlFile(htmlContent, 'AI虚拟架构组周报');
                  Modal.destroyAll();
                }}
              >
                下载HTML
              </Button>
            </div>
            <CancelBtn />
          </div>
        ),
      });
      
      message.success('生成周报HTML成功');
    } catch (error) {
      console.error('生成周报HTML失败:', error);
      message.error('生成周报HTML失败');
    } finally {
      setGenerateHtmlLoading(false);
    }
  };

  // 处理编辑按钮点击
  const handleEdit = (record: TaskReport) => {
    setEditingRecord(record);
    form.setFieldsValue(record);
    setEditModalVisible(true);
  };

  // 处理编辑弹窗确认
  const handleEditConfirm = async () => {
    try {
      const values = await form.validateFields();
      
      if (!editingRecord?.id) {
        message.error('编辑记录ID不存在');
        return;
      }

      // 调用更新API
      await updateTaskReport(editingRecord.id, values);
      
      message.success('编辑成功');
      setEditModalVisible(false);
      setEditingRecord(null);
      form.resetFields();
      fetchData(); // 刷新数据
    } catch (error) {
      console.error('编辑失败:', error);
      message.error('编辑失败');
    }
  };

  // 处理编辑弹窗取消
  const handleEditCancel = () => {
    setEditModalVisible(false);
    setEditingRecord(null);
    form.resetFields();
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div className="p-6">
      <Alert
        message={<div style={{ fontSize: '16px', fontWeight: 500 }}>提醒： 模型处理需要时间，请耐心等待...</div>}
        description={
          <ol style={{ margin: '8px 0 0 0', paddingLeft: '20px' }}>
            <li style={{ padding: '6px 0' }}>  请先点击「AI生成周报明细」按钮，等待系统生成任务报告数据 </li>
            <li style={{ padding: '6px 0' }}>  数据生成后，点击「AI生成周报HTML」按钮生成完整的周报页面</li>
            <li style={{ padding: '6px 0' }}>  可先下载预览周报，确认后在历史周报月报页面上传</li>
          </ol>
        }
        type="info"
        showIcon
        style={{ 
          marginBottom: '16px', 
          borderLeft: '4px solid #1890ff',
          boxShadow: '0 2px 8px rgba(0,0,0,0.09)'
        }}
      />
      <Card
        title="AI任务报告分析"
        extra={
          <Space>
            <Button
              type="primary"
              icon={<FileTextOutlined />}
              loading={generateDetailLoading}
              onClick={handleGenerateDetail}
            >
              AI生成周报明细
            </Button>
            <Button
              type="primary"
              icon={<FileExcelOutlined />}
              loading={generateHtmlLoading}
              onClick={handleGenerateHtml}
            >
              AI生成周报HTML
            </Button>
            <Button
              icon={<DownloadOutlined />}
              loading={exportLoading}
              onClick={handleExportExcel}
            >
              导出Excel
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1870 }}
          pagination={{
            pageSize: 5,
            showSizeChanger: false,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
          bordered
          size="middle"
          style={{ 
            overflowX: 'auto',
            overflowY: 'auto',
            maxHeight: 'calc(100vh - 300px)'
          }}
          components={{
            header: {
              cell: (props: React.HTMLAttributes<HTMLTableHeaderCellElement>) => (
                <th
                  {...props}
                  style={{
                    ...props.style,
                    backgroundColor: '#e6e9f0',
                    fontWeight: 600,
                    color: '#262626',
                    fontSize: '15px',
                    padding: '12px 8px'
                  }}
                />
              ),
            },
          }}
        />
      </Card>
      
      {/* 编辑弹窗 */}
      <Modal
        title="编辑任务报告"
        open={editModalVisible}
        onCancel={handleEditCancel}
        width={800}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          style={{ maxHeight: '500px', overflowY: 'auto' }}
        >
          <Form.Item
            label="任务标题"
            name="title"
            rules={[{ required: true, message: '请输入任务标题' }]}
          >
            <Input.TextArea rows={2} placeholder="请输入任务标题" />
          </Form.Item>
          
          <Form.Item
            label="负责人"
            name="receiver"
            rules={[{ required: true, message: '请输入负责人' }]}
          >
            <Input placeholder="请输入负责人" />
          </Form.Item>
          
          <Form.Item
            label="状态"
            name="status"
          >
            <Input placeholder="请输入状态" />
          </Form.Item>
          
          <Form.Item
            label="需求类型"
            name="type"
          >
            <Input placeholder="请输入需求类型" />
          </Form.Item>
          
          <Form.Item
            label="子类型"
            name="subType"
          >
            <Input placeholder="请输入子类型" />
          </Form.Item>
          
          <Form.Item
            label="业务部门"
            name="busiDepartment"
          >
            <Input placeholder="请输入业务部门" />
          </Form.Item>
          
          <Form.Item
            label="业务目标"
            name="busiGoal"
          >
            <Input.TextArea rows={3} placeholder="请输入业务目标" />
          </Form.Item>
          
          <Form.Item
            label="IT部门"
            name="itDepartment"
          >
            <Input placeholder="请输入IT部门" />
          </Form.Item>
          
          <Form.Item
            label="预计进展"
            name="originalPlan"
          >
            <Input.TextArea rows={4} placeholder="请输入预计进展" />
          </Form.Item>
          
          <Form.Item
            label="实际进展"
            name="actualProgress"
          >
            <Input.TextArea rows={4} placeholder="请输入实际进展" />
          </Form.Item>
          
          <Form.Item
            label="存在问题"
            name="problems"
          >
            <Input.TextArea rows={4} placeholder="请输入存在问题" />
          </Form.Item>
          
          <Form.Item
            label="AI评价"
            name="progressRating"
          >
            <Input.TextArea rows={3} placeholder="请输入AI评价" />
          </Form.Item>
          
          <Form.Item
            label="AI总结"
            name="progressSummary"
          >
            <Input.TextArea rows={4} placeholder="请输入AI总结" />
          </Form.Item>
          
          <Form.Item
            label="周期结束日期"
            name="periodEndDate"
          >
            <Input placeholder="请输入周期结束日期" />
          </Form.Item>
        </Form>
        
        <div style={{ 
          display: 'flex', 
          justifyContent: 'flex-end', 
          gap: '8px',
          marginTop: '24px',
          paddingTop: '16px',
          borderTop: '1px solid #f0f0f0'
        }}>
          <Button onClick={handleEditCancel}>
            取消
          </Button>
          <Button type="primary" onClick={handleEditConfirm}>
            保存
          </Button>
        </div>
      </Modal>
    </div>
  );
};

export default AiReportsPage;
